import PlatformBase from './PlatformBase';
import { GameConfig } from '../../Config/GameConfig';
import { CallBackHandler } from '../PoolObj/CallBackHandler';
import { DataMgr, PlayerData } from '../../Manager/DataManager';
import { PlayerParams } from '../../Config/DataConfig';
import { EventType } from '../../../Game/Config/GameEnum';
import { EventManager } from '../../Manager/EventManager';
import { GravityModel } from '../SDK/GravityModel';
import { VideoEvent } from '../../../Data/Types';
import { AudioManager } from '../../Manager/AudioManager';
import { RequestUrl, WebRequestHttp } from '../../Handle/WebRequest';
/* eslint-disable */
declare let wx: any;

export default class WXPlatform extends PlatformBase {
  shareImgId: string = '';
  shareImgUrl: string = '';

  resumeBannerTimer: number = -1;
  initFramework() {
    this.platformApi = wx || window['wx'];
    try {
      this.platformApi = window['wx'].getSystemInfoSync();
    } catch (e) {
      window['wx'].getSystemInfo({
        success(res) {
          this.systemInfo = res;
        },
      });
    }
    this.$videoId = 'adunit-758fb19ccb769884';
    this.$adIndex = null;
    this.registerEvent();
  }

  registerEvent() {
    console.log('wx registerEvent');

    // console.log(window['wx'], window['wx'].onShareAppMessage);
    const self = this;

    console.log('wx showShareMenu');
    window['wx'].showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
    });

    console.log('wx updateShareMenu');
    window['wx'].updateShareMenu({
      withShareTicket: true,
      success() {},
    });

    console.log('wx onShareAppMessage');
    window['wx'].onShareAppMessage(() => {
      // 用户点击了“转发”按钮
      // const share = {
      //   title: '代码调用分享',
      //   imageUrl: self.shareImgUrl, // 图片 URL
      //   query: 'key1=val1&key2=val2',
      // };
      // const data = window['wx'].uma.trackShare(share);
      return {
        title: '要我说,这关没人能过',
        imageUrl: '', // 图片 URL
      };
    });

    console.log('wx onUserCaptureScreen');
    window['wx'].onUserCaptureScreen(() => {
      // 用户截屏了
      window['wx'].showShareImageMenu({
        path: '',
      });
    });

    console.log('wx onShow');
    window['wx'].onShow(() => {});

    // try {
    console.log('wx登录');
    this.login();
    // } catch {
    //   console.log('wx登录失败');
    // }
    // setInterval(this.checkSession, 60);
    setTimeout(this.checkParam.bind(this), 60000);
  }

  /** 登录 */
  login() {
    const self = this;
    window['wx'].login({
      success(res) {
        if (res.code) {
          // 发起网络请求
          self.$appCode = res.code;
          // window['wx'].authorize({
          //   scope: 'scope.userInfo',
          //   success() {
          //     // 用户同意授权用户信息
          //     self.getUserData();
          //   },
          // });
          // self.checkSession();
          window['wx'].getSetting({
            success(res) {
              console.log(`wx登录成功`);

              if (res.authSetting['scope.userInfo'] === true) {
                self.getUserData();
              } else {
                console.log(`wx请求授权`);
                EventManager.Ins().emit(EventType.LOGIN, { code: self.$appCode });
                const button = window['wx'].createUserInfoButton({
                  type: 'text',
                  text: '',
                  style: {
                    left: 0,
                    top: 0,
                    width: 2000,
                    height: 2000,
                    lineHeight: 40,
                    backgroundColor: '#ff000000',
                    color: '#ffffff',
                    textAlign: 'center',
                    fontSize: 16,
                    borderRadius: 4,
                  },
                });
                button.onTap((res) => {
                  // console.log(res);
                  if (res.errMsg.indexOf(':ok') > -1 && !!res.rawData) {
                    // 获取用户信息
                    wx.getUserInfo({
                      success: (res) => {
                        // 已经授权，直接获取用户信息
                        const userInfo = res.userInfo;
                        DataMgr.changePlayerAttr(PlayerParams.nickname, userInfo.nickName, true);
                        DataMgr.changePlayerAttr(PlayerParams.avatarUrl, userInfo.avatarUrl, true);
                        // G_Config.PlayerParam[PlayerParam.NICKNAME] = userInfo.nickName;
                        // G_Config.PlayerParam[PlayerParam.AVATARURL] = userInfo.avatarUrl;
                        // HttpConfig.Singleton.request(RequestUrl.USERS_UPDATEINFOCACHE, { nickname: userInfo.nickName, avatarURL: userInfo.avatarUrl });
                        // GravityModel.I.initialize();
                      },
                    });
                    button.destroy();
                  } else {
                    button.destroy();
                    // GravityModel.I.initialize();
                  }
                });
              }
            },
          });
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      },
      fail(err) {
        console.log('登录失败！' + err.errMsg);
      },
    });
  }
  getUserData() {
    // const func = ()=>{
    //   if(GravityModel.I.setuped) GravityModel.I.initialize();
    //   else setTimeout(func.bind(this), 1000);
    // }
    const self = this;
    window['wx'].getUserInfo({
      success: (res) => {
        // 已经授权，直接获取用户信息
        const userInfo = res.userInfo;
        DataMgr.changePlayerAttr(PlayerParams.nickname, userInfo.nickName, true);
        DataMgr.changePlayerAttr(PlayerParams.avatarUrl, userInfo.avatarUrl, true);
        WebRequestHttp.requestPost(
          RequestUrl.api_url + RequestUrl.USERS_UPDATEINFOCACHE,
          {
            platform: 'wechat',
            session_key: PlayerData.get(PlayerParams.session_key),
            nickname: userInfo.nickName,
            avatarURL: userInfo.avatarUrl,
          },
          null
        );
        EventManager.Ins().emit(EventType.LOGIN, { code: self.$appCode });
        // GravityModel.I.initialize();
        // func.call(this)
      },
      fail: () => {
        EventManager.Ins().emit(EventType.LOGIN, { code: self.$appCode });
      },
    });
  }
  /** 检测登录状态 */
  checkSession() {
    const self = this;
    window['wx'].checkSession({
      success() {
        // session_key 未过期，并且在本生命周期一直有效
        // if (constD.inGameState == 0) constD.inGameState = 1;
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        self.login(); // 重新登录
      },
    });
  }

  /** 直接转发 */
  shareMessage() {
    const self = this;
    window['wx'].shareAppMessage({
      title: '能过的IQ都在200以上',
      imageUrl: '',
    });
  }

  openVibrateShort() {
    GameConfig.setting.ShakeState &&
      window['wx'].vibrateShort({
        type: 'heavy',
        success() {
          // console.log('ovs s');
        },
        fail() {
          // console.log('ovs f');
        },
        complete() {
          // console.log('ovs c');
        },
      });
  }

  openVibrateLong(t: number = 15) {
    // gameD.SharkState &&
    GameConfig.setting.ShakeState && window['wx'].vibrateShort(t);
  }

  sendDesktop(e) {}
  /** 调起添加桌面图标 */

  hasShortcutInstalled(e) {}
  /** 是否已添加桌面图标 */
  getIsDesktop() {}
  /** 播放音乐 */

  playMusic(e, t) {}
  /** 暂停音乐播放 */
  stopMusic() {}
  /** 播放音效 */

  playSound(e, t) {}
  /** 暂停音效 */

  stopSound(e) {}
  /** 退出游戏 */
  exitGame() {}
  /** 提示窗口 */

  // showToast(e) {}
  createLupingBtn() {}
  createMoreGameBtn() {}

  loadBanner(bIndex: number) {}

  resumeBanner() {}

  showBanner(isShow: boolean) {
    const self = this;
    if (isShow) {
      if (this.$bannerAd)
        if (this.$bannerAd[0]) this.$bannerAd[0].show();
        else self.loadBanner(0);
    } else if (this.$bannerAd) {
      if (this.$bannerAd[0]) this.$bannerAd[0].hide();
      else {
        this.resumeBannerTimer > 0 && clearTimeout(this.resumeBannerTimer);
        // this.resumeBannerTimer = setTimeout(this.resumeBanner, 4200);
        if (this.$bannerInit) {
          this.$bannerInit = false;
          this.loadBanner(0);
        }
      }
    }
  }

  openBanner(e) {}
  hideBanner() {}

  checkParam() {
    window['adLock'] = false;
    this.loadVideo();
    // this.loadInsertAd();
  }

  loadVideo() {
    const self = this;
    if (this.$videoAd == null) {
      const obj = {
        adUnitId: this.$videoId,
      };
      this.$videoAd = wx.createRewardedVideoAd(obj);

      const onError = (res: any) => {
        // ManagetCtrl.Ins.uiMgr.showAlert('正在加载视频广告');
        console.log('正在加载视频广告');
        console.log(res.errMsg, res.errCode);
      };

      const onClose = (res: any) => {
        console.log('用户关闭广告', JSON.stringify(res));
        if (res.isEnded) {
          // do something
          // ManagetCtrl.Ins.uiMgr.showAlert('成功获取激励奖励');
          self.adFinish();
          self.showToast('获得广告奖励', '', 1000);
        } else {
          console.log('用户未看完广告');
          self.showToast('未看完广告,无法获取奖励', '', 1000);
        }
        // canShow = false;
        // if (res.count) {
        //   // 在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
        //   // 判断观看了几次广告
        // }
      };

      this.$videoAd.onError(onError.bind(this));
      this.$videoAd.onClose(onClose.bind(this));

      this.$videoAd.load();
    }
  }

  showVideo(index: VideoEvent) {
    console.log('展示广告', index);
    if (window['adLock']) {
      this.showToast('广告正在加载中', '', 1000);
      return;
    }

    const self = this;
    if (window['ad']) {
      // ManagetCtrl.Ins.uiMgr.showAlert('请勿频繁点击');
      // console.log('请勿频繁点击', index);
      this.showToast('请勿频繁点击', '', 1000);
      return;
    }
    window['ad'] = true;
    setTimeout(() => {
      window['ad'] = false;
    }, 3000);
    // console.log('广告id', this.$videoId[0], index);

    const obj = {
      adUnitId: this.$videoId,
    };
    this.$adIndex = index;
    // let canShow = true;
    if (this.$videoAd == null) {
      this.$videoAd = wx.createRewardedVideoAd(obj);
      console.log('广告ad', this.$videoAd, index);
      const onLoad = () => {
        // ManagetCtrl.Ins.uiMgr.showAlert('观看完成可获得激励');
        console.log('观看完成可获得激励');
        // canShow &&
        // self.$videoAd.show();
        AudioManager.Singleton.readyPlay = true;
      };

      const onError = (res: any) => {
        // ManagetCtrl.Ins.uiMgr.showAlert('正在加载视频广告');
        console.log('正在加载视频广告');
        console.log(res.errMsg, res.errCode);
      };

      const onClose = (res: any) => {
        console.log('用户关闭广告', JSON.stringify(res));
        // GameManager.I.gameShow();
        if (res.isEnded) {
          // do something
          // ManagetCtrl.Ins.uiMgr.showAlert('成功获取激励奖励');
          console.log('广告回调', index);
          self.adFinish();
          self.showToast('获得广告奖励', '', 1000);
        } else {
          console.log('用户未看完广告');
          self.showToast('未看完广告,无法获取奖励', '', 1000);
        }

        // AudioManager.Singleton.loadAndPlayMusic(SoundCode.BGM);
        // G_Config.MusicState && AudioManager.I.audioSource.play();

        AudioManager.Singleton.checkBgm();
        // canShow = false;
        // if (res.count) {
        //   // 在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
        //   // 判断观看了几次广告
        // }
      };
      // this.$videoAd.offLoad(onLoad.bind(this));
      // this.$videoAd.offError(onError.bind(this));
      // this.$videoAd.offClose(onClose.bind(this));

      this.$videoAd.onLoad(onLoad.bind(this));
      this.$videoAd.onError(onError.bind(this));
      this.$videoAd.onClose(onClose.bind(this));

      // this.$videoAd.load();

      // 创建激励视频广告实例，提前初始化
      // let videoAd = wx.createRewardedVideoAd({
      //   adUnitId: 'adunit-15a2600412e205b2'
      // })

      // 用户触发广告后，显示激励视频广告
      // this.$videoAd.show().catch(() => {
      //   // 失败重试
      //   this.$videoAd
      //     .load()
      //     .then(() => this.$videoAd.show())
      //     .catch((err) => {
      //       console.error('激励视频 广告显示失败', err);
      //     });
      // });
    }
    //  else {
    //   this.$videoAd.show();
    // }
    // AudioManager.I.readyPlay = true;
    this.$videoAd.show().catch(() => {
      // 失败重试
      this.$videoAd
        .load()
        .then(() => this.$videoAd.show())
        .catch((err) => {
          console.error('激励视频 广告显示失败', err);
        });
    });
    return true;
  }

  // showVideo(index: number) {
  //   const self = this;
  //   if (window['ad']) {
  //     // ManagetCtrl.Ins.uiMgr.showAlert('请勿频繁点击');
  //     console.log('请勿频繁点击', index);
  //     return;
  //   }
  //   window['ad'] = true;
  //   setTimeout(() => {
  //     window['ad'] = false;
  //   }, 2000);
  //   const obj = {
  //     adUnitId: this.$videoId,
  //   };
  //   this.$adIndex = index;
  //   if (this.$videoAd == null) {
  //     this.$videoAd = window['wx'].createRewardedVideoAd(obj);
  //     const onLoad = () => {
  //       // ManagetCtrl.Ins.uiMgr.showAlert('观看完成可获得激励');
  //       console.log('观看完成可获得激励');
  //       self.$videoAd.show();
  //     };

  //     const onError = (res: any) => {
  //       // ManagetCtrl.Ins.uiMgr.showAlert('正在加载视频广告');
  //       console.log('正在加载视频广告');
  //       console.log(res.errMsg, res.errCode);
  //     };

  //     const onClose = (res: any) => {
  //       console.log('用户关闭广告', JSON.stringify(res));
  //       if (res.isEnded) {
  //         // do something
  //         // ManagetCtrl.Ins.uiMgr.showAlert('成功获取激励奖励');
  //         self.adFinish();
  //       } else {
  //         console.log('用户未看完广告');
  //       }
  //       // if (res.count) {
  //       //   // 在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
  //       //   // 判断观看了几次广告
  //       // }
  //     };
  //     // this.$videoAd.offLoad(onLoad.bind(this));
  //     // this.$videoAd.offError(onError.bind(this));
  //     // this.$videoAd.offClose(onClose.bind(this));

  //     this.$videoAd.onLoad(onLoad.bind(this));
  //     this.$videoAd.onError(onError.bind(this));
  //     this.$videoAd.onClose(onClose.bind(this));

  //     this.$videoAd.load();
  //   } else {
  //     this.$videoAd.show();
  //   }
  //   return true;
  // }
  showInsertAd() {}

  loadNativeAd(e) {}

  showNativeInBox(e, t, i) {}

  showNativeInsert(e, t) {}

  showNativeInsertAd(e, i, a) {}

  showNativeBannerAd(e, i, a) {}

  showSmallNative(e) {}
  recordScreen() {}
  removeScreen() {}
  pauseRecord() {}

  showTTBanner(e) {}

  reportRankingList(e) {}
  getRankingList() {}
  showQQBox() {}

  navigateToVideo(e) {}
  jumpToDY() {}
  // eslint-disable-next-line @typescript-eslint/ban-types
  loadSubpackage(bundleName: string, callback: () => unknown = null) {
    const loadTask = window['wx'].loadSubpackage({
      name: bundleName, // name 可以填 name 或者 root

      success(res) {
        // 分包加载成功后通过 success 回调
        callback && callback();
      },

      fail(res) {
        // 分包加载失败通过 fail 回调
      },
    });

    loadTask.onProgressUpdate((res) => {
      // console.log('下载进度', res.progress);
      // console.log('已经下载的数据长度', res.totalBytesWritten);
      // console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
    });
  }

  showElectPortalAd(e) {}

  showwxCustomAd(e, t) {}

  openContent(e, t) {}
  closeContent() {}

  showNativeIcon(e, t) {}

  showNativeBanner(e, t) {}

  showPlayBanner(e) {}
  getHttpId() {}

  onHasShortcutInstalled(e) {}
  trackEvent(e, o = null) {
    window['wx'].uma && window['wx'].uma.trackEvent(e, o);
  }

  requestHttpGet(url: string, data: any, callback: CallBackHandler, headers?: { [key: string]: string }): void {
    window['wx'].request({
      method: 'GET',
      url: url,
      data: data,
      success(res) {
        callback.execute(res);
      },
    });
  }

  requestHttpPost(url: string, data: any, callback: CallBackHandler, headers?: { [key: string]: string }): void {
    window['wx'].request({
      method: 'POST',
      url: url,
      data: data,
      success(res) {
        callback.execute(res);
      },
    });
  }

  showToast(e, i, d) {
    window['wx'].showToast({
      title: `${e}`,
      icon: `${i}`,
      duration: d,
    });
  }
}
